<!--
 * @Author: xiezhiquan3878
 * @Date: 2024-06-22 19:32:51
 * @LastEditors: zhayang 1063975710@qq.com
 * @LastEditTime: 2024-07-06 20:57:33
 * @FilePath: \heart-backed\src\views\banner\index.vue
 * @Description: 图片上传
-->
<template>
  <div class="avatar-uploader-box">
    <el-upload
      class="avatar-uploader"
      :name="'filePath'"
      :multiple="false"
      :headers="postheaders"
      :data="postData"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      accept=".jpg,.jpeg,.png,.gif"
      :before-upload="beforeAvatarUpload"
      :http-request="handleUploadImg"
    >
      <div
        v-if="imageUrl && imgShow"
        class="w-120 h-120 relative"
      >
        <img
          :src="imageUrl"
          class="fit"
          @click.stop
        />
        <div
          class="cursor-pointer absolute bottom-0 left-0 full-w h-34 bg-#00000080 text-14 c-#fff center"
          @click.stop="deletePic"
        >
          删除
        </div>
      </div>

      <div
        v-else
        class="up-show flex flex-col flex-nowrap"
      >
        <i
          :class="upIcon"
          class="plus-icon"
        ></i>
        <div class="up-text">{{ upText }}</div>
        <div class="sub-up-text">{{ subUpText }}</div>
      </div>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { getStsApi } from '@/api/upload'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    // 地址是否完整
    integrityAddress: {
      type: String,
      default: '1'
    },
    upIcon: {
      type: String,
      default: 'el-icon-plus avatar-uploader-icon'
    },
    upText: {
      type: String,
      default: ''
    },
    subUpText: {
      type: String,
      default: ''
    },
    imgShow: Boolean
  },
  data() {
    return {
      // 图片上传
      process: '',
      imageUrl: '',
      postheaders: {
        'Auth-Token': getToken()
      },
      stsData: {},
      fileData: {},
      postData: {
        key: '',
        policy: '',
        OSSAccessKeyId: '',
        signature: '',
        'x-oss-security-token': '' // 使用STS签名时必传。
      }
    }
  },
  watch: {
    url: {
      handler(nv, oldName) {
        if (nv) {
          if (this.integrityAddress === '0') {
            if (nv.indexOf('http') !== -1) {
              this.imageUrl = nv
            } else {
              this.imageUrl = process.env.VUE_APP_FILE_API + nv
            }
          } else {
            this.imageUrl = nv
          }
        } else {
          this.imageUrl = ''
        }
      },
      immediate: true
    }
  },
  created() {
    this.setData()
  },
  methods: {
    generateUUID() {
      const timestamp = Date.now().toString(16)
      const random = Math.random().toString(16).slice(2)
      return `${timestamp}${random}`
    },
    setData() {
      getStsApi()
        .then((res) => {
          this.stsData = res.data
          // this.process = this.stsData.host
          // this.process = '/up-api/'
        })
        .catch(() => {})
    },
    // 截取上传文件后缀
    getSuffix(filename) {
      const pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos !== -1) suffix = filename.substring(pos)
      return suffix
    },
    handleAvatarSuccess(res, file) {
      // console.log('handleAvatarSuccess', res, file)
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.$emit('getImg', this.imageUrl, file.name, file)
    },
    beforeAvatarUpload(file) {
      this.fileData = file
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M
    },
    handleUploadImg(file) {
      const that = this
      const signature = this.stsData.mp.signature
      const ossAccessKeyId = this.stsData.body.AccessKeyId
      const policy = this.stsData.mp.policy
      const key =
        this.stsData.file_path +
        this.generateUUID() +
        '.' +
        this.getSuffix(file.file.name)
      const securityToken = this.stsData.body.SecurityToken
      const formData = new FormData()
      formData.append('name', file.file.name) // 文件名称
      formData.append('key', key) // 存储在oss的文件路径
      formData.append('OSSAccessKeyId', ossAccessKeyId) // //accessKeyId
      formData.append('policy', policy) // policy
      formData.append('Signature', signature) // 签名
      formData.append('x-oss-security-token', securityToken) // 使用STS签名时必传。
      formData.append('success_action_status', 200)
      formData.append('file', file.file, file.file.name) // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传即可

      return new Promise((resolve, reject) => {
        axios
          .post(that.stsData.host, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'Auth-Token': getToken()
            }
          })
          .then((rep) => {
            // console.log('rep', rep)
            if (rep.status === 200) {
              that.imageUrl = that.stsData.host + '/' + key
            }
            resolve(rep)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    deletePic() {
      this.$emit('deleteImg')
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader-box {
  vertical-align: top;
  ::v-deep {
    .avatar-uploader {
      width: 100%;
      height: 100%;
      .el-upload {
        border: 1px dashed #dcdcdc;
        border-radius: 6px;
        width: 100%;
        height: 100%;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #04d1b8;
        }
      }
      .up-show {
        height: 100%;
        background-color: #f4f5f9;
        display: flex;
        justify-content: center;
        align-items: center;
        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 100%;
          text-align: center;
        }
      }
    }
    .avatar {
      width: 100%;
      height: 100%;
      display: block;
    }

    .el-upload-dragger {
      width: 100%;
      height: 100%;
      background-color: #f4f5f9;
      border: 0;
    }
  }
}
.plus-icon {
  font-size: 28px;
  font-weight: 600;
  color: #1c1f23 !important;
  text-align: center;
}

.up-show {
  color: #1c1f23;
}

.up-text {
  margin-top: 10px;
  font-weight: 400;
  font-size: 10px;
  color: #6a6b6c;
  line-height: 12px;
}
.sub-up-text {
  font-weight: 400;
  font-size: 10px;
  color: #6a6b6c;
  line-height: 12px;
}
</style>
